package com.situ.gym.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.situ.gym.mapper.RoleMapper;
import com.situ.gym.mapper.RolePermissionMapper;
import com.situ.gym.pojo.Role;
import com.situ.gym.pojo.Role;
import com.situ.gym.mapper.RoleMapper;
import com.situ.gym.pojo.RolePermission;
import com.situ.gym.pojo.query.RoleQuery;
import com.situ.gym.pojo.vo.PermissionVO;
import com.situ.gym.service.IPermissionService;
import com.situ.gym.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.gym.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gao
 * @since 2025-09-01
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private IPermissionService permissionService;

    @Override
    public IPage<Role> list(RoleQuery roleQuery) {
        IPage<Role> page  = new Page<>(roleQuery.getPage(), roleQuery.getLimit());
        return roleMapper.list(page, roleQuery);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        roleMapper.deleteAll(ids);
    }

    @Override
    public Map<String, Object> selectAssignedPermission(Integer roleId) {
        //拿到所有权限树形结构
        List<PermissionVO> permissionVOList = permissionService.selectPermissionTree();
        //根据roleId查询这个角色下面已经分配的所有权限
        List<Long> assignedPermissionIdList = rolePermissionMapper.selectByRoleId(roleId);

        Map<String, Object> map = new HashMap<>();
        map.put("permissionVOList", permissionVOList);
        map.put("assignedPermissionIdList", assignedPermissionIdList);
        return map;
    }

    @Override
    public void assignPermission(Long roleId, Long[] permissionIds) {
        //在role_permission表里面先删除roleId已经分配的权限
        rolePermissionMapper.deleteByRoleId(roleId);
        //给这个角色重新分配权限
        for (Long permissionId : permissionIds) {
            RolePermission rolePermission = new RolePermission();
            rolePermission.setRoleId(roleId);
            rolePermission.setPermissionId(permissionId);
            rolePermissionMapper.insert(rolePermission);
        }
    }


}
